package jwlee.testthread;

import java.util.ArrayList;
import java.util.List;

public class MethodExecutant {

	List<Method> methodList;

	public MethodExecutant() {
		methodList = new ArrayList<Method>();
	}

	public void andMethod(Method method) {
		if (method != null) {
			methodList.add(method);
		}
	}

	public void executeAll() {
		if (methodList == null) {
			return;
		}
		for (int i = 0; i < methodList.size(); i++) {
			((Method) (methodList.get(i))).doSomething();
		}
	}

	public static void main(String[] args) {
		MethodExecutant executant = new MethodExecutant();
		executant.andMethod(executant.new Method(executant, "method1"));
		executant.andMethod(executant.new Method(executant, "method2"));
		executant.andMethod(executant.new Method(executant, "method3"));
		executant.executeAll();
	}

	private class Method {
		private String methodname;

		MethodExecutant executant;

		boolean isSynchronized = true;

		Method(MethodExecutant executant, String methodname) {
			this.executant = executant;
			this.methodname = methodname;
		}

		public String getName() {
			return methodname;
		}

		public void doSomething() {
			System.out.println(methodname + " doSomething...");

			new Thread() {
				public void run() {
					for (int i = 0; i < 500; i++) {
						System.out.println(methodname + " -> " + i);
					}
					if (isSynchronized) {
						synchronized (executant) {
							System.out.println(methodname + " notify executant");
							executant.notify();// ���̻߳���
						}
					}
				}
			}.start();

			if (isSynchronized) {
				synchronized (executant) {
					try {
						System.out.println(methodname + " wait executant");
						executant.wait();// ���̵߳ȴ�
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
